/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cassys.action;

import cassys.datatransferobjects.PeerAssessmentDTO;
import cassys.delegates.ModuleDelegate;
import cassys.delegates.PeerAssessmentDelegate;
import java.util.Random;

/**
 *
 * @author User
 */
public class PeerAssessmentAction {
   
    private String moduleCode;
    private PeerAssessmentDTO peerAssess;
    private String peerAssessId;
    private boolean isUpdate = false;
    private PeerAssessmentDelegate paDelegate = new PeerAssessmentDelegate();

    public boolean isIsUpdate() {
        return isUpdate;
    }

    public void setIsUpdate(boolean isUpdate) {
        this.isUpdate = isUpdate;
    }

    public String getModuleCode() {
        return moduleCode;
    }

    public void setModuleCode(String moduleCode) {
        this.moduleCode = moduleCode;
    }

    public PeerAssessmentDTO getPeerAssess() {
         if(findPAByModule(moduleCode) != null){
            peerAssess = findPAByModule(moduleCode);
         }
        return peerAssess;
    }

    public void setPeerAssess(PeerAssessmentDTO peerAssess) {
        this.peerAssess = peerAssess;
    }
    
     public String create() throws Exception {
         System.out.println("create");
        return "configure";
    }
     
     public String edit() throws Exception {
         System.out.println("edit");
        peerAssess = findPAByModule(moduleCode);
        if (peerAssess != null) {
            isUpdate = true;
        }
        return "configure";
    }

    public String update() throws Exception {
        peerAssess.setModuleCode(moduleCode);
        //peerAssess.setPaEvalutionList(null);
        try{
            if (peerAssess.getPeerAssessId() != null && peerAssess.getPeerAssessId().length() > 0) {
            paDelegate.updatePA(peerAssess);
            } else {
                peerAssess.setPeerAssessId("PA" + getRandomNumber());
                paDelegate.insertPA(peerAssess);
            }
       } catch (Exception e) {
            e.printStackTrace();
        }
        return edit();
    }
    
    public PeerAssessmentDTO findPAByModule(String moduleCode){
        PeerAssessmentDTO pa = null;
        try{
            pa = paDelegate.findPAByModule(moduleCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pa;
    }
    
     protected int getRandomNumber() {
        Random randomGenerator = new Random();
        return randomGenerator.nextInt();
    }
}
